package com.va1m.demo.service.impl;

import com.va1m.demo.entity.User;
import com.va1m.demo.mapper.UserMapper;
import com.va1m.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 处理用户信息的service
 * @author Admin
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User getUserInfo(Integer userId) {
        User user = userMapper.selectById(userId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH：mm：ss");
        Date expireDate = user.getExpireDate();
        //如果用户未充值过会员 则过期时间显示为空
        if(expireDate == null){
            user.setFormatDate("非会员用户");
            return user;
        }
        //不为空时进行格式化
        String format = simpleDateFormat.format(expireDate);
        user.setFormatDate(format);
        return user;
    }

    @Override
    public Boolean addMoney(Integer userId, BigDecimal money) {
        User user = userMapper.selectById(userId);
        if(user == null || user.getId() == null){
            throw new RuntimeException("用户不存在");
        }
        if(money.compareTo(new BigDecimal(0)) < 1){
            throw new RuntimeException("充值金额不能为负数");
        }
        user.setBalance(user.getBalance().add(money));
        int success = userMapper.updateById(user);
        if(success < 0){
            throw new RuntimeException("充值失败");
        }
        return true;
    }
}
